<?php
declare (strict_types=1);

namespace app\scan_bag\service;

use app\admin\model\base\User;
use app\admin\model\iot\IntegralOrder;
use app\BaseService;
use job\RabbitmqJob;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Log;
use think\response\Json;

/**
 * V1取袋公用服务层
 */
class ScanBagV1Service extends BaseService
{

    /**
     * 获取用户取袋次数并同步用户到客户
     * @param $user_id
     * @param $mac_id
     * @return Json
     */
    public function userScanNum($user_id, $mac_id): Json
    {
        //获取用户信息
        $User = User::getIdUserInfo($user_id);
        if (!$User) {
            return jsonReturn(0, [], '用户信息错误');
        }
        //请求参数
        $params = [
            'user' => [
                'id' => $User['openid'], //自营公众号open_id
                'avatar' => $User['avatar'],
                'original' => [
                    'openid' => $User['openid'],
                    'nickname' => $User['nickname'],
                    'sex' => 0,
                    'language' => '',
                    'city' => '',
                    'province' => '',
                    'country' => '',
                    'headimgurl' => $User['avatar']
                ]]
        ];
        $task_num_url = config('sys_config.WsScanBag.v1_iot_pay_uri') . '/api/merb/paly_new/' . $mac_id;
        $result = httpPost($task_num_url, ['json' => $params], ['content-type' => 'application/json']);
        $content = json_decode($result['content'], true);
        if ($result['status_code'] == 200 && $content) {
            return jsonReturn(1, [$content]);
        } else {
            return jsonReturn(0, ['msg' => $content['error']] ?? '请求失败');
        }
    }

    /**
     * 获取用户取袋次数并同步用户到客户
     * @param int $user_id
     * @param string $mac_id
     * @return array
     */
    public function userScanNum2(int $user_id, string $mac_id): array
    {
        //获取用户信息
        $User = User::getIdUserInfo($user_id);
        if (!$User) {
            return ['bool' => false, 'data' => [], 'msg' => '用户不存在'];
        }
        //请求参数
        $params = [
            'user' => [
                'id' => $User['openid'], //自营公众号open_id
                'avatar' => $User['avatar'],
                'original' => [
                    'openid' => $User['openid'],
                    'nickname' => $User['nickname'],
                    'sex' => 0,
                    'language' => '',
                    'city' => '',
                    'province' => '',
                    'country' => '',
                    'headimgurl' => $User['avatar']
                ]]
        ];
        $task_num_url = config('sys_config.WsScanBag.v1_iot_pay_uri') . '/api/merb/paly_new/' . $mac_id;
        $result = httpPost($task_num_url, ['json' => $params], ['content-type' => 'application/json']);
        $content = json_decode($result['content'], true);
        if ($result['status_code'] == 200 && $content) {
            return ['bool' => true, 'data' => $content, 'msg' => '成功'];
        }
        $msg = $content['error'] ?? '请求失败';
        return ['bool' => false, 'data' => [], 'msg' => $msg];
    }

    /**
     * 调物联网接口进行出袋操作(取袋码)
     * @param string $waycode
     * @param string $way
     * @param int $pay_type
     * @return Json
     */
    public function outBagWaycodeToV1(string $waycode, string $way,int $pay_type=1): Json
    {
        //通过waycode获取信息
        $WaycodeInfo = ScanBagV2Service::getBagOutWaycodeParams($waycode);
        if (!$WaycodeInfo or $WaycodeInfo['way'] != $way) {
            return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
        }
        if(isset($WaycodeInfo['pay_type'])){
            $pay_type = $WaycodeInfo['pay_type'];
        }
        //获取用户信息
        $openid = $WaycodeInfo['userInfo']['openid'];
        $mac_id = $WaycodeInfo['mac_id'];
        //验证ticket
        if(isset($WaycodeInfo['ticket'])){
            //验证ticket 缓存
            $capture_step_check = (new V1_Way_1_0Service())->verifyCaptureStep($WaycodeInfo['ticket']);
            if (!$capture_step_check) {
                return jsonReturn(0, [], '请进行图像码验证!');
            }
        }
        //IOT自营公众号
        $sys_config = config('sys_config.WsOfficialAccount');
        //组装调用iot所需要的数据
        $params_iot = [
            'appid' => $sys_config['appid'],
            'user_id' => $openid,
            'mac_id' => $mac_id,
        ];
        $sign = arrayDataSignature($params_iot);
        $params_iot['sign'] = $sign;
        $params_ready = [
            'form_params' => $params_iot
        ];
        $out_bag_url = config('sys_config.WsScanBag.v1_iot_pay_uri') . '/api/merb/thirdPartyOrder';
        $result = httpPost($out_bag_url, $params_ready);
        log::write($result,"下单到V1");
        $content = json_decode($result['content'], true);
        if ($result['status_code'] == 200 && $content['code'] == 200) {
            try {
                if($pay_type ==2){
                    //写入积分订单表
                    $res = (new IntegralOrder())->save([
                        'order_no'=>$content['order_no']??'aaaaaa001',
                        'point'=>100,
                        'unionid'=>$WaycodeInfo['userInfo']['unionid']??'bbbb001',
                    ]);
                    //同步积分
                    $params =[
                        'unionid'=>$WaycodeInfo['userInfo']['unionid'],
                        'type'=>10,
                        'bonus_points'=>100,
                        'action'=>0
                    ];
                    (new V1_Way_1_0Service)->updateMyPoints($params);
                }
                //推送至数据大屏队列
                $msg = ['mac_id' => $params_iot['mac_id'], 'openid' => $params_iot['user_id']];
                $run = RabbitmqJob::getInstance();
                $run->sendMsg('V1PushToDataScreen', '', $msg);
            } catch (\Exception $exception) {
                Log::write($exception->getMessage(), '出袋推送至数据大屏失败');
            }
            //删除取代码
            Cache::delete($waycode);
            //生成数据缓存，方便用户查询是否出袋成功(缓存50s)
            Cache::set(WS_USER_ID.'_c','1',50);
            return jsonReturn(1, [], '出袋成功');
        } else {
            $msg = $content['msg'] ?? '出袋失败';
            //生成数据缓存，方便用户查询是否出袋成功(缓存50s)
            Cache::set(WS_USER_ID.'_c','0',30);
            return jsonReturn(0, [], $msg);
        }
    }

    /**
     * 发起微信支付至V1
     * @param int $user_id
     * @param string $mac_id
     * @return Json
     */
    public function payOrderToV1(int $user_id, string $mac_id): Json
    {
        //获取机器售卖策略
        $machine_sale_url = config('sys_config.WsScanBag.v1_iot_pay_uri') . '/api/merb/getMachineSale/' . $mac_id;
        $sale_id_result = httpGet($machine_sale_url);
        $sale_id = 0;
        if ($sale_id_result['status_code'] == 200 && !empty($sale_id_result['content'])) {
            $sale_id = json_decode($sale_id_result['content'], true)['saleid'];
        }
        //获取用户信息
        $User = User::getIdUserInfo($user_id);
        $params = [
            'openid' => $User['openid'],//自营公众号open_id
            'is_duobao' => 0,
            'saleid' => $sale_id, //machine_sale_package表id666
            'pay_pattern' => 1,
            'pay_type' => 3
        ];
        $params_ready = [
            'json' => $params
        ];
        $pay_url = config('sys_config.WsScanBag.v1_iot_pay_uri') . '/api/merb/payordernew';
        $result = httpPost($pay_url, $params_ready, ['content-type' => 'application/json']);
        $content = json_decode($result['content'], true);
        if ($result['status_code'] == 200 && isset($content['wxjs'])) {
            return jsonReturn(1, [$content['wxjs']]);
        } else {
            return jsonReturn(0, ['msg' => $content['error']] ?? '请求失败');
        }
    }

    /**
     * 做积分任务
     */
    public function doPointTask($task_id,$content)
    {


    }

}
